// 创建本地服务
const fs = require('fs');
const http = require('http'); // 加载http模块
const url = require('url');  // 加载url模块
// import replaceTemplate from './modules/replaceTemplate';
const replaceTemplate = require('./modules/replaceTemplate');
// 存放到全局上下文方便调用
const data = fs.readFileSync(`./dev-data/data.json`, 'utf-8');
const dataObj = JSON.parse(data);
const tempOverview = fs.readFileSync(`${__dirname}/index.html`, 'utf-8');
const tempProduct = fs.readFileSync(`${__dirname}/templates/template-product.html`, 'utf-8');
const tempCard = fs.readFileSync(`${__dirname}/templates/template-card.html`, 'utf-8');
console.log(tempOverview);

// 创建服务器
const server = http.createServer((req, res) => {
    // 根据请求的url，找到对应的文件
    const { pathname, query } = url.parse(req.url, true)
    if (pathname === '/' || pathname === '/overview' || pathname === '/node-farm') {
        const cardsHtml = dataObj.map(el => replaceTemplate(tempCard, el));
        const output = tempOverview.replace('{%PRODUCT_CARDS%}', cardsHtml);
        // console.log(cardsHtml); //  {%PRODUCT_CARDS%} 替换后的html
        res.end(output)
    } else if (pathname === '/product') {
        res.writeHead(200, { 'Content-type': 'text/html' });
        const productID = dataObj[query.id];
        // 渲染模板
        const output = replaceTemplate(tempProduct, productID);
        res.end(output);
    } else if (pathname === '/api') {
        res.writeHead(200, { 'Content-type': 'application/json' });
        res.end(data);

    } else {
        res.writeHead(404, {
            'Content-Type': 'text/html',
            'my-own-header': 'hello world'
        });
        res.end('<h1>404 Not Found</h1>');
    }
})
// 绑定并监听端口 
server.listen(3000, '127.0.0.1', () => {
    console.log('server is running at http://127.0.0.1:3001');
})
